package Leetcode.动态规划;

import java.util.Arrays;

/**
 * @Author: kirito
 * @Date: 2024/8/17 16:31
 * @Description:
 */

public class 背包01问题 {
    public static void main(String[] args) {
        int[] values = {3, 6, 9, 7}; // 物品的价值
        int[] weights = {2, 3, 4, 2};   // 物品的重量
        int capacity = 5;             // 背包的容量
        int maxValue = knapsack(values, weights, capacity);
        System.out.println("最大价值为: " + maxValue);
    }
    public static int knapsack(int[] values, int[] weights, int capacity) {
        int n = values.length;
        int[][] dp = new int[n + 1][capacity + 1];
        // 初始化dp数组
        //第一行第一列为0
/*        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= capacity; j++) {
                if (i == 0 || j == 0) {
                    dp[i][j] = 0;
                }
            }
        }*/

        // 填充dp数组
        //dp i j代表前i个物品装到容量j里的最大价值
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= capacity; j++) {
                if (weights[i - 1] <= j) {
                    dp[i][j] = Math.max(values[i - 1] + dp[i - 1][j - weights[i - 1]], dp[i - 1][j]);
                } else {
                    dp[i][j] = dp[i - 1][j];
                }
            }
        }
        for (int i = 0; i <= n; i++) {
            System.out.println(Arrays.toString(dp[i]));
        }

        int[] buy = new int[n + 1];
        int j = capacity;
        for (int i = n; i >= 1; i--) {
            if (dp[i][j] == dp[i - 1][j]) {
                buy[i] = 0;
            } else {
                buy[i] = 1;
                j -= weights[i - 1];
            }
        }
        System.out.println(Arrays.toString(buy));

        // 返回dp数组的最后一个元素
        return dp[n][capacity];
    }
}
